<template>
  <div>
    <el-tabs
      type="border-card"
      v-model="activname"
      @tab-click="handleSwitchTabs"
    >
      <el-tab-pane
        v-for="item in tabList"
        :key="item.name"
        :disabled="tableInfo.loading"
        v-model="item.name"
        :label="item.title"
        :name="item.name"
      />
      <BasicForm
        v-loading="formLoading"
        ref="formData"
        formItemWidth="100px"
        needSetSearchFields
        :menuId="menuId"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="handleClearForm"
        @getFormData="getFormData"
        @getSearchFormFields="getSearchFormFields"
      />
      <el-card class="sourcing-table-card" shadow="never">
        <el-row slot="header" type="flex" justify="space-between" align="middle">
          <div><span>数据列表 </span><el-checkbox v-if="isAccepted" v-model="wholeOrder">选整单</el-checkbox></div>
          <div>
            <el-button
              v-for="(item, index) in getOperateBtns(status)"
              size="mini"
              :key="index"
              :loading="item.loading"
              @click="item.fn"
              >{{ item.content }}
            </el-button>
          </div>
        </el-row>
        <BasicList
          :loading="tableInfo.loading"
          :selection-change="selectionChange"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
          :total="total"
          :tableHeight="493"
          :pagination="pagination"
          @pageChange="handlePageChange"
          @pageSizeSelect="handlePageSizeChange"
          @sortChangeFn="sortChangeFn"
        />
      </el-card>
    </el-tabs>
    <!-- 订货异常 取消询价 -->
    <InquiryDialog
      :visible.sync="inqueryFlag"
      :setdiolagdata="setdiolagdata"
    />
    <!-- 转派 -->
    <DedicatedDialog
      :visible.sync="allocationFlag"
      ref="childRecorduser"
      :setdiolagdata="setdiolagdata"
    />
    <!-- 转派记录 -->
    <RecordDialog
      :visible.sync="recordFlag"
      :setdiolagdata="setdiolagdata"
    />
    <!-- 订货异常记录 -->
    <AbnormalrecordDialog
      :visible.sync="abnorRecordFlag"
      :setdiolagdata="setdiolagdata"
    />
    <!-- 查看附件 -->
    <AttachmentDialog
      :visible.sync="qualifieDialogVisible"
      :fileGroupId="fileGroupId"
    />
    <!-- 字段显示设置 -->
    <FieldSettingDialog
      :visible.sync="fieldSettingVisible"
      @ok-handler="getTableColumns"
    />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import BasicList from '@sourcing/components/BasicList';
import BasicForm from '@sourcing/components/BasicForm';
import BasicPage from '@/mixins/sourcing/basicPage';
import SearchFields from '@/mixins/sourcing/searchFields';
import TableColumns from '@/mixins/sourcing/tableColumns';
import InquiryDialog from '../elDialog/InquiryDialog';
import DedicatedDialog from '../elDialog/DedicatedDialog';
import RecordDialog from '../elDialog/RecordDialog';
import AbnormalrecordDialog from '../elDialog/AbnormalrecordDialog';
import AttachmentDialog from '@sourcing/components/AttachmentDialog';
import { createExcelByExport } from '@/utils/bizUtils';
import { handleOpenNewPageByName } from '@sourcing/utils';
import {
  exportDemandOrderService,
  getOrderListService,
  updateOrderSkuCodeService
} from '@/api/sourcing/demandInquery';
import { TAB_LIST, FORM_ITEMS } from './constants';

export default {
  mixins: [
    BasicPage,
    TableColumns,
    SearchFields
  ],
  components: {
    BasicList,
    BasicForm,
    InquiryDialog,
    DedicatedDialog,
    RecordDialog,
    AbnormalrecordDialog,
    AttachmentDialog, // 查看附件
  },
  data () {
    return {
      menuId: 102,
      formItems: FORM_ITEMS,
      wholeOrder: false, // 是否整单
      fileGroupId: null,
      qualifieDialogVisible: false,
      recordFlag: false,
      inqueryFlag: false,
      abnorRecordFlag: false,
      allocationFlag: false,
      status: '', // 询价状态
      activname: '', // 当前选中的
      tabList: TAB_LIST,
      setdiolagdata: {
        tabtype: 2,
      },
    };
  },
  computed: {
    ...mapState('sourcing/demandInquery', {
      inqueryBtnLoading: (state) => state.inqueryBtnLoading,
      acceptBtnLoading: (state) => state.acceptBtnLoading,
    }),
    // 已受理状态
    isAccepted () {
      return this.status == 20;
    },
  },
  methods: {
    ...mapActions('sourcing/demandInquery', [
      'handleOrderInquiryList', // 生成询价单据
      'acceptanceList', // 受理
      'cancelAcceptanceList', // 取消受理
    ]),
    init () {
      this.getTableColumns();
      const { sts, billNo, productCode } = this.$route.query;
      if (sts) {
        if (sts == 60) {
          this.formData.billNo = billNo;
          this.formData.productCode = productCode;
        }
        this.activname = sts;
        this.status = sts;
        this.formData.orderGoodsStatus = [Number(sts)];
        this.getTableData();
      } else {
        this.handleEmptyTable()
      }
    },
    // 清空表格数据
    handleEmptyTable () {
      this.tableInfo.list = []
      this.total = 0
    },
    // 获取查询条件
    getSearchParameters () {
      const { orderGoodsDate, requireArrivalDatetime, auditorDate, targetDate } = this.formData;
      const [orderGoodsDateStart = '', orderGoodsDateEnd = ''] = orderGoodsDate || [];
      const [requireArrivalDatetimeStart = '', requireArrivalDatetimeEnd = ''] = requireArrivalDatetime || [];
      const [auditorDateStart = '', auditorDateEnd = ''] = auditorDate || [];
      const [targetDateStart = '', targetDateEnd = ''] = targetDate || [];
      return _.omit({
        ...this.formData,
        orderGoodsDateStart,
        orderGoodsDateEnd,
        requireArrivalDatetimeStart,
        requireArrivalDatetimeEnd,
        auditorDateStart,
        auditorDateEnd,
        targetDateStart,
        targetDateEnd,
        status: this.status
      }, 'orderGoodsDate', 'auditorDate', 'targetDate', 'requireArrivalDatetime')
    },
    // 查询订货信息
    async getTableData (pageNum) {
      const formData = this.getSearchParameters();
      const omitForm = {
        ..._.omit(formData, 'orderBy', 'orderByType')
      }
      if (!formData.status && Object.values(omitForm).every(item => (!item || item.length == 0))) {
        return this.$message.warning('请选择查询条件')
      }
      if (pageNum) {
        this.pagination.pageNum = pageNum;
      }
      const data = { ...formData, ...this.pagination };
      const res = await getOrderListService(data, state => { this.tableInfo.loading = state })
      if (res?.data) {
        const { list, total } = res.data
        this.tableInfo.list = list;
        this.total = total;
      }
    },
    // 切换tab
    handleSwitchTabs (target) {
      this.$refs['formData'].handleResetForm();
      this.status = target.name;
      this.wholeOrder = false;
      if (!target.name) {
        this.handleEmptyTable()
      }
      this.formatFormItems();
      this.$nextTick(() => {
        this.handlePageChange(1);
      });
    },
    // 格式化表单信息
    formatFormItems () {
      const needSelect = !this.status || this.status == 40
      this.formItems = _.cloneDeep(this.formItems).map(item => {
        if (item.prop == 'orderGoodsStatus') {
          item.disabled = !needSelect
          item.options = this.status == 40
            ? _.cloneDeep(item.selectData).filter(item => [40, 70].includes(item.value))
            : item.selectData
        }
        return item;
      })
    },
    // 渲染表头操作按钮
    getOperateBtns (status) {
      const actionList = [
        { content: '受理', fn: this.acceptHandler, loading: this.acceptBtnLoading, status: ['10'] },
        { content: '转派', fn: this.tranPersonnelHandler, status: ['10'] },
        { content: '转派记录', fn: this.tranRecordHandler, status: ['10'] },
        { content: '取消', fn: this.cancelHandler, status: ['20'] },
        { content: '订货异常', fn: this.inquiryExceptionHandler, status: ['10', '20'] },
        {
          content: '采购询价',
          fn: this.offlinePurchaseHandler,
          loading: this.inqueryBtnLoading,
          status: ['20', '30', '40']
        },
        { content: '订货异常记录', fn: this.abnormalRecordHandler, status: ['50'] },
      ];
      const actionBtnList = actionList.filter(item => item.status.includes(status));
      const defaultBtnList = [
        { content: '导出', fn: this.exportDataHandler, loading: this.exportLoading },
        { content: '字段显示设置', fn: this.fieldSettingHandler }
      ]
      if (!status) {
        return [
          { content: '转派记录', fn: this.tranRecordHandler },
          ...defaultBtnList
        ];
      }
      return actionBtnList.concat(defaultBtnList);
    },
    // 受理
    acceptHandler () {
      const entridlist = this.dataProcessFn();
      const data = {
        entryIds: entridlist
      };
      const cb = (res) => {
        this.verifyIsMulticode(
          res,
          () => {
            this.$message.success(res.msg);
            this.getTableData();
          },
          data
        )
      };
      if (entridlist && entridlist.length > 0) {
        this.acceptanceList({
          payload: {
            data,
            cb
          }
        });
      }
    },
    // 订货异常
    inquiryExceptionHandler () {
      const checkdata = this.checkDataHandler();
      if (checkdata) {
        this.inqueryFlag = true;
      }
    },
    // 异常记录
    abnormalRecordHandler () {
      const checkdata = this.checkDataHandler();
      if (checkdata) {
        this.abnorRecordFlag = true;
      }
    },
    // 转派人员
    tranPersonnelHandler () {
      const checkdata = this.checkDataHandler();
      if (checkdata) {
        this.$refs.childRecorduser.initqueryHrUserList();
        this.allocationFlag = true;
      }
    },
    // 转派记录
    tranRecordHandler () {
      const checkdata = this.checkDataHandler();
      if (checkdata) {
        this.recordFlag = true;
      }
    },
    // 数据处理
    checkDataHandler () {
      const entridlist = this.dataProcessFn();
      if (entridlist && entridlist.length > 0) {
        this.setdiolagdata.selectionChangeval = entridlist;
        return true;
      } else {
        return false;
      }
    },
    // 数据导出
    async exportDataHandler () {
      const res = await exportDemandOrderService(
        this.getSearchParameters(),
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ res, excelTitle: '订货需求列表' });
      }
    },
    // 取消
    cancelHandler () {
      const entridlist = this.dataProcessFn();
      const cb = (res) => {
        this.$message.success(res.msg);
        this.getTableData();
      };
      const data = {
        entryIds: entridlist
      };
      if (entridlist && entridlist.length > 0) {
        this.cancelAcceptanceList({
          payload: {
            data,
            cb
          }
        });
      }
    },
    // 线下采购
    offlinePurchaseHandler () {
      // wholeOrder  是否整单 是为true，否为false
      // entryIds  体id集合 是否整单为否时必传
      // billId    单据id   是否整单为是时必传
      // this.status == 20
      if (this.tableInfo.selection.length === 0) {
        return this.$message('请选择单据');
      }
      const billId = this.tableInfo.selection.map((item) => item.orderGoodsId)
      const entryIds = this.tableInfo.selection.map((item) => item.orderGoodsEntryId)
      if ([...new Set(billId)].length > 1) {
        return this.$message('请选择同一单据');
      }
      const orderParams = {
        wholeOrder: this.wholeOrder,
        billId: billId[0],
        entryIds
      }
      this.orderInqueryAction(orderParams)
    },
    // 采购询价接口调用
    orderInqueryAction (orderGoodsInfo) {
      const cb = (res) => {
        this.verifyIsMulticode(
          res,
          () => {
            const { sourcingBillId, readOnly } = res?.data
            const isEdit = this.status != '40' && !readOnly;
            sessionStorage.setItem(
              'detailInfo',
              JSON.stringify({
                pageType: 2,
                isEdit,
                sourcingBillId,
                isDemand: true
              })
            );
            this.getTableData();
            if (isEdit) {
              handleOpenNewPageByName(this, 'demandPurchaseDetail');
            } else {
              sessionStorage.setItem('isCompleteWinBill', 1);
              handleOpenNewPageByName(this, 'orderCalibrationView');
            }
          },
          orderGoodsInfo
        )
      };
      this.handleOrderInquiryList({
        payload: {
          data: orderGoodsInfo,
          cb
        }
      });
    },
    // 表头排序
    sortChangeFn (row) {
      this.formData.orderBy = row.prop;
      if (row.order == 'ascending') {
        this.formData.orderByType = 'asc';
      } else if (row.order == 'descending') {
        this.formData.orderByType = 'desc';
      } else {
        this.formData.orderBy = '';
        this.formData.orderByType = '';
      }
      this.getTableData();
    },
    // 接口数据处理
    dataProcessFn () {
      let entridlist = [];
      const datalist = this.tableInfo.selection;
      if (datalist.length == 0) {
        return this.$message('请选择商品');
      }
      datalist.forEach((item) => {
        entridlist.push(item.orderGoodsEntryId);
      });
      return entridlist;
    },
    // 重置表单
    handleClearForm () {
      this.$nextTick(() => {
        if (!this.status) {
          this.formData.orderGoodsStatus = [];
        } else {
          if (this.status == 40) {
            this.formData.orderGoodsStatus = [40, 70];
          } else {
            this.formData.orderGoodsStatus = [Number(this.status)];
          }
        }
      });
    },
    // 获取商品资质
    queryGoodsQualificationsAction (row) {
      this.fileGroupId = row.fileGroupId;
      this.qualifieDialogVisible = true;
    },
    // 获取分类Id
    getCategoryUuid (val) {
      this.formData.categoryCode = val;
    },
    // 修改询价需求商品为主码商品
    async updateInquirySkuCode (params) {
      const res = await updateOrderSkuCodeService({
        ...params
      })
      if (res) {
        this.$message.success('操作成功')
        this.getTableData();
      }
    },
    // 校验是否一物多码
    verifyIsMulticode (res, callback, params) {
      const { data } = res
      if (data && typeof data == 'string') {
        this.$confirm(data, '提示', { type: 'warning' }).then(() => {
          this.updateInquirySkuCode(params)
        }).catch(() => {});
      } else {
        callback()
      }
    },
  }
};
</script>
